package com.luoran.bartalks.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.core.UserContext;
import com.luoran.bartalks.core.ext.Pageable;
import com.luoran.bartalks.entity.BaseInfo;
import com.luoran.bartalks.entity.biz.BtCodingRule;
import com.luoran.bartalks.entity.biz.BtPlanDetails;
import com.luoran.bartalks.entity.biz.BtProject;
import com.luoran.bartalks.entity.biz.BtProjectMember;
import com.luoran.bartalks.entity.biz.UserInfo;
import com.luoran.bartalks.service.IBtCodingRuleService;
import com.luoran.bartalks.service.IBtPlanDetailsService;
import com.luoran.bartalks.service.IBtProjectMemberService;
import com.luoran.bartalks.service.IBtProjectService;
import com.luoran.bartalks.service.IUserService;
import com.luoran.bartalks.utils.EnumBillType;

//项目的Controller
@Controller
@RequestMapping("/project")
public class BtProjectAction implements Pageable {

	@Autowired
	private IBtProjectService projectService;

	@Autowired
	private IBtCodingRuleService codingRuleService;

	@Autowired
	private IUserService userService;

	@Autowired
	private IBtPlanDetailsService planService;

	@Autowired
	private IBtProjectMemberService memberService;

	private static final Logger log = LoggerFactory.getLogger(BtProjectAction.class);

	// 项目管理页面列表页面
	@RequestMapping
	public String queryPosition() {
		log.info("跳转到>>项目管理页面");

		return "projectPlanManage/project-list";
	}

	// 项目管理列表数据
	@Override
	public PageQuery<? extends BaseInfo> getQueryList(PageQuery<? extends BaseInfo> pageQuery) {
		@SuppressWarnings("unchecked")
		Map<String, String> map = (Map<String, String>) pageQuery.getParas();
		map.put("companyId", UserContext.get().getCompanyId());// 添加查询参数（公司ID）
		if (StringUtils.isEmpty(pageQuery.getOrderBy())) {
			pageQuery.setOrderBy("create_date DESC");
		}
		return projectService.getQueryList(pageQuery);
	}

	// 检测当前单据类型是否有编码规则
	@RequestMapping("/checkCodingRule")
	@ResponseBody
	public JSONObject checkCodingRule() {
		log.info(" 判断>>>>当前单据类型是否有编码规则");
		List<BtCodingRule> rules = codingRuleService.checkCodingRule(EnumBillType.PROJECT.getName(),
				UserContext.get().getCompanyId());
		JSONObject result = new JSONObject();
		if (rules.size() == 0) {
			result.put("flag", false);
			result.put("msg", "未找到项目已启用的编码规则,请先添加或启用!");
			log.info(" >>>>没有找到编码规则");
			return result;
		}
		result.put("flag", true);
		log.info(" >>>>检测到编码规则");
		return result;
	}

	// 跳转到新增页面
	@RequestMapping("/newProject")
	public String addProject(Model model) {
		log.info("获取>>项目编码");
		JSONObject projectCode = codingRuleService.generateCoding(EnumBillType.PROJECT,
				UserContext.get().getCompanyId());
		model.addAttribute("projectCode", projectCode);

		model.addAttribute("title", "新增项目");
		model.addAttribute("companyName", UserContext.get().getCompanyName());
		model.addAttribute("companyId", UserContext.get().getCompanyId());
		model.addAttribute("creatorName", UserContext.get().getAlias());
		model.addAttribute("creatorId", UserContext.get().getId());

		log.info("获取>>>公司所有成员");
		List<UserInfo> members = userService.getProjectMembers(UserContext.get().getCompanyId());// 获取公司所有成员
		model.addAttribute("members", members);// 成员
		model.addAttribute("project", new BtProject());

		log.info("跳转到>>>新增项目页面!");
		return "projectPlanManage/addProject";
	}

	/**
	 * 新增项目
	 * 
	 * @param BtProject
	 * @return
	 */
	@RequestMapping("/addProject")
	@ResponseBody
	public JSONObject addManage(BtProject project) {

		log.info(">>>新增项目");
		JSONObject result = new JSONObject();

		if (StringUtils.isEmpty(project.getProjectName())) {
			result.put("flag", false);
			result.put("msg", "项目名称不能为空!");
			return result;
		}
		if (StringUtils.isEmpty(project.getManagerId())) {// 保存项目管理员ID
			result.put("flag", false);
			result.put("msg", "请选择管理员!");
			return result;
		}
		if (StringUtils.isEmpty(project.getMemberId())) {// 保存项目成员ID
			result.put("flag", false);
			result.put("msg", "请选择项目成员!");
			return result;
		}
		if (StringUtils.isEmpty(project.getProjectDesc())) {
			result.put("flag", false);
			result.put("msg", "请填写项目简介");
			return result;
		}

		// 根据管理员ID字符串获取管理员名称
		String[] managerIdArr = project.getManagerId().split(",");

		List<String> managers = new ArrayList<String>();
		for (String managerId : managerIdArr) {
			managers.add(userService.getUser(managerId).getNick());
		}
		String managerNameStr = org.apache.commons.lang.StringUtils.join(managers, ",");
		project.setManagerName(managerNameStr);

		// 根据成员ID字符串,获取成员名称
		String[] memberIdArr = project.getMemberId().split(",");

		List<String> members = new ArrayList<String>();
		for (String memberId : memberIdArr) {
			// 成员ID即用户ID.,拿到每一个成员的昵称
			members.add(userService.getUserInfo(memberId).getNick());
		}
		String memberNameStr = org.apache.commons.lang.StringUtils.join(members, ",");
		project.setMemberName(memberNameStr);
		project.setStarted(0);
		project.setCreateDate(new Date());
		project.setStatus(0);

		String uuid = projectService.addProject(project);
		if (uuid != null) {
			result.put("flag", true);
			result.put("msg", "操作成功!");
			result.put("projectId", uuid);
			result.put("projectName", project.getProjectName());
			log.info("新建项目>>>成功");
			return result;
		} else {
			result.put("flag", false);
			result.put("msg", "操作失败!");
			log.info("新建项目>>>失败");
			return result;
		}

	}

	// 获取项目信息
	@RequestMapping("/editProject/{id}")
	public String getProjectInfo(@PathVariable("id") String id, Model model) {
		log.info("获取项目信息>>>>");
		BtProject project = projectService.getProjectInfo(id);

		model.addAttribute("id", project.getId());// ID
		model.addAttribute("projectCode", project.getProjectCode());// 编码
		model.addAttribute("projectName", project.getProjectName());// 项目名称
		model.addAttribute("companyName", project.getCompanyName());// 公司
		model.addAttribute("creatorName", project.getCreatorName());// 创建人
		model.addAttribute("projectDesc", project.getProjectDesc());// 描述
		model.addAttribute("project", project);
		model.addAttribute("title", "编辑项目");

		log.info("获取项目成员信息>>>>>");
		List<BtProjectMember> memberProjects = memberService.getProjectMember(id);// 通过项目ID查询成员信息

		List<String> managersId = new ArrayList<String>();// 接受管理员ID字符串
		List<String> membersId = new ArrayList<String>();// 接受普通成员id字符串

		if (memberProjects != null) {
			for (BtProjectMember memberProject : memberProjects) {
				if (0 == memberProject.getMemberType()) {// 如果是管理员记录
					managersId.add(memberProject.getMemberId());
				} else if (1 == memberProject.getMemberType()) {// 如果是普通成员记录
					membersId.add(memberProject.getMemberId());
				}
			}
		}

		String managerIdStr = org.apache.commons.lang.StringUtils.join(managersId, ","); // 管理员ID拼成的字符串
		String memberIdStr = org.apache.commons.lang.StringUtils.join(membersId, ","); // 成员ID拼成的字符串

		log.info("获取>>>项目成员ID");
		model.addAttribute("memberIdStr", memberIdStr);
		log.info("获取>>>项目管理员ID");
		model.addAttribute("managerIdStr", managerIdStr);

		log.info("获取>>公司所有成员");
		List<UserInfo> members = userService.getProjectMembers(UserContext.get().getCompanyId());// 获取公司成员
		model.addAttribute("members", members);
		log.info("跳转到>>>编辑项目页面!");
		return "projectPlanManage/editProject";
	}

	// 编辑项目
	@RequestMapping("/updateProject")
	@ResponseBody
	public JSONObject updateProject(BtProject project) {
		JSONObject result = new JSONObject();

		if (StringUtils.isEmpty(project.getProjectName())) {
			result.put("flag", false);
			result.put("msg", "项目名称不能为空!");
			return result;
		}

		if (StringUtils.isEmpty(project.getManagerId())) {// 保存项目管理员ID
			result.put("flag", false);
			result.put("msg", "请选择管理员!");
			return result;
		}

		if (StringUtils.isEmpty(project.getMemberId())) {// 保存项目成员ID
			result.put("flag", false);
			result.put("msg", "请选择项目成员!");
			return result;
		}

		if (StringUtils.isEmpty(project.getProjectDesc())) {
			result.put("flag", false);
			result.put("msg", "请填写项目简介");
			return result;
		}

		// 根据管理员ID字符串获取管理员名称
		String[] managerIdArr = project.getManagerId().split(",");
		List<String> managers = new ArrayList<String>();
		for (String managerId : managerIdArr) {
			managers.add(userService.getUser(managerId).getNick());
		}
		String managerNameStr = org.apache.commons.lang.StringUtils.join(managers, ",");
		project.setManagerName(managerNameStr);

		// 根据成员ID字符串,获取成员名称
		String[] memberIdArr = project.getMemberId().split(",");
		List<String> members = new ArrayList<String>();
		for (String memberId : memberIdArr) {
			// 成员ID即用户ID.,拿到每一个成员的昵称
			members.add(userService.getUserInfo(memberId).getNick());
		}
		String memberNameStr = org.apache.commons.lang.StringUtils.join(members, ",");
		project.setMemberName(memberNameStr);

		log.info("编辑项目>>>>>");

		int count = projectService.updateProject(project);

		if (count == 1) {
			result.put("flag", true);
			result.put("msg", "操作成功,请查看项目明细");
			return result;
		} else {
			result.put("flag", false);
			result.put("msg", "操作失败");
			return result;
		}
	}

	// 查询项目下是否有计划.如果没有项目才能删除
	@RequestMapping("/searchPlan/{id}")
	@ResponseBody
	public JSONObject searchPlan(@PathVariable("id") String projectId) {
		JSONObject result = new JSONObject();
		// 查询项目下是否有计划
		List<BtPlanDetails> plans = planService.findPlanByProjectId(projectId);
		if (plans.size() == 0) {
			result.put("flag", true);
			return result;
		} else {
			result.put("flag", false);
			result.put("msg", "当前项目正在进行中,无法删除!");
			return result;
		}

	}

	// 删除
	@RequestMapping("/delete/{id}")
	@ResponseBody
	public JSONObject deleteProject(@PathVariable("id") String id) {
		JSONObject result = new JSONObject();
		BtProject project = new BtProject();
		try {
			List<BtPlanDetails> plans = planService.findPlanByProjectId(id);
			if(plans!=null) {
				for (BtPlanDetails btPlanDetails : plans) {
					btPlanDetails.setStatus(5);// 置为删除
					planService.updatePlan(btPlanDetails);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("flag", false);
			result.put("msg", "操作失败!");
		}
		project.setId(id);
		project.setStatus(1);// 置为删除
		int count = projectService.deleProject(project);
		if (count != 1) {
			result.put("flag", false);
			result.put("msg", "操作失败!");
			return result;
		}
		result.put("flag", true);
		result.put("msg", "操作成功!");
		return result;

	}

	// 项目的启动.暂停
	@RequestMapping("/start")
	@ResponseBody
	public JSONObject startProject(BtProject project) {
		JSONObject obj = new JSONObject();

		int count = projectService.startProject(project);
		if (count == 1) {
			obj.put("flag", true);
			obj.put("msg", "操作成功");
			return obj;
		} else {
			obj.put("flag", false);
			obj.put("msg", "操作失败");
			return obj;
		}
	}

}
